/**
 * JsonSerializer.java
 *
 * @author tianli
 * 
 * @date 2011-3-14
 * 
 */
package com.baidu.common.json;

import java.util.Collection;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

import com.baidu.common.utils.AppLog;

/**
 * @author tianli
 * 
 */
public class JsonSerializer {
    
    private static final String TAG = JsonSerializer.class.getName();
    
    private static JsonSerializer instance = new JsonSerializer();
    
    private ObjectMapper impl;
    
    public static JsonSerializer getInstance() {
        if (instance == null) {
            instance = new JsonSerializer();
        }
        return instance;
    }
    
    JsonSerializer() {
        try {
            impl = new ObjectMapper();
        } catch (Exception e) {
            e.printStackTrace();
        }
        DeserializationConfig cfg = impl.getDeserializationConfig();
        cfg.set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    
    public String serialize(Object object) {
        try {
            return impl.writeValueAsString(object);
        } catch (Exception e) {
            AppLog.error(TAG, e.getMessage(), e);
            return null;
        }
    }
    
    public <T> T deserialize(String json, Class<T> clazz) {
        if (json == null || json.length() == 0)
            return null;
        try {
            return impl.readValue(json, clazz);
        } catch (Exception e) {
            AppLog.error(TAG, e.getMessage(), e);
            return null;
        }
    }
    
    public <T extends Collection<?>, V> Object deserialize(String json, Class<T> collection,
        Class<V> data) {
        try {
            return impl.readValue(json, TypeFactory.collectionType(collection, data));
        } catch (Exception e) {
            AppLog.error(TAG, e.getMessage(), e);
            return null;
        }
    }
}
